package com.fanshuai.springcloud.config;

import com.fanshuai.springcloud.domain.Book;
import com.fanshuai.springcloud.domain.User;
import com.fanshuai.springcloud.handler.WebFluxHandler;
import com.fanshuai.springcloud.web.response.CallResult;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class MainConfig {
    @Resource
    private WebFluxHandler webFluxHandler;

    @Bean
    public RouterFunction<ServerResponse> routerFunction() {
        return RouterFunctions
          .route(RequestPredicates.GET("/webflux/books"), serverRequest -> {
              CallResult<List<Book>> result = webFluxHandler.books(serverRequest);
              return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                      .body(Mono.just(result), CallResult.class);

        }).andRoute(RequestPredicates.GET("/webflux/users"), serverRequest -> {
              CallResult<List<User>> result = webFluxHandler.users(serverRequest);
              return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                       .body(Mono.just(result), CallResult.class);
        });
    }

    @Bean
    public HttpMessageConverters messageConverters() {
        List<HttpMessageConverter> converters = new ArrayList<>();
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        converters.add(new FormHttpMessageConverter());
        converters.add(new ByteArrayHttpMessageConverter());
        converters.add(new MappingJackson2HttpMessageConverter());

        return new HttpMessageConverters(converters.toArray(new HttpMessageConverter[0]));
    }
}
